package cn.com.generaldata.os.service.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.sql.SqlTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import cn.com.generaldata.jsme_indicator_system.entity.StatSystem;

import com.google.common.collect.Maps;

@Service
public class StatSystemService {

	@Autowired
	private SqlTemplate sqlTemplate;
	
	@Autowired
	private Dao dao;

	public Map<String, String> getStatSystemMap() {
		Map<String, String> re = Maps.newLinkedHashMap();

		List<StatSystem> statSystems = dao.query(StatSystem.class, Cnd.orderBy().asc("no"));

		for (StatSystem statSystem : statSystems) {
			re.put(statSystem.getId().toString(), statSystem.getName());
		}
		return re;
	}

	public StatSystem getStatSystemByName(String name) {
		return dao.fetch(StatSystem.class, Cnd.where("name", "=", name));
	}
	
	public List<StatSystem> getStatSystem(String userId, String roleId){
		String sql = "select *  from T_STAT_SYSTEM where id in (select rt.stat_system  from TBL_USER_INDUSTRY ui "
              + " inner join TBL_DUSTRY_REPORT ir on ir.industry_id = ui.industry_id inner join Tbl_Report_Type rt "
              + " on rt.id = ir.report_type_id where ui.user_id = @userId) ";
		
		Map params = new HashMap();
		
		
		String roleSql = "select * from t_report_type_unit_type where report_unit_type = '" + roleId + "'";
		Record record = sqlTemplate.queryForRecord(roleSql, null, null);;
		
		if (record!=null){
			sql = "select *  from T_STAT_SYSTEM where id in (select rt.stat_system from  Tbl_Report_Type rt" +
					" inner join t_report_type_unit_type tut  on tut.report_unit_type = @roleId   and tut.report_type_id = rt.id )";
			params.put("roleId", roleId);
		}else{
			params.put("userId", userId);
		}

		
		List<Record> list = sqlTemplate.queryRecords(sql, null, params);
		
		List<StatSystem> sysList = new ArrayList<StatSystem>();
		for (Record re :  list){
			StatSystem sys = new StatSystem();
			sys.setId(re.getInt("id"));
			sys.setName(re.getString("name"));
			sysList.add(sys);
		}
		
		return sysList;
    }
}
